import Cookies from 'js-cookie'

// 定义 cookies 对象的接口
interface CookieUtils {
  set: (name?: string, value?: string, cookieSetting?: Record<string, any>) => void
  get: (name?: string) => string
  getAll: () => Record<string, string>
  remove: (name?: string) => void
}

// 提取基础名称
const BASE_NAME = import.meta.env.VITE_APP_BASE_NAME

// 封装 cookie key 的生成逻辑
const getCookieKey = (name: string = 'default'): string => `${BASE_NAME}-${name}`

/**
 * @description 存储 cookie 值
 * @param {String} name cookie name
 * @param {String} value cookie value
 * @param {Object} cookieSetting cookie 配置项
 */
const setCookie = (name?: string, value?: string, cookieSetting?: Record<string, any>): void => {
  const defaultSetting = { expires: 1, sameSite: 'lax' as const }
  Cookies.set(getCookieKey(name), value || '', { ...defaultSetting, ...cookieSetting })
}

/**
 * @description 拿到 cookie 值
 * @param {String} name cookie name
 */
const getCookie = (name?: string): string => {
  return Cookies.get(getCookieKey(name)) || ''
}

/**
 * @description 拿到 cookie 全部的值
 */
const getAllCookies = (): Record<string, string> => {
  return Cookies.get()
}

/**
 * @description 删除 cookie
 * @param {String} name cookie name
 */
const removeCookie = (name?: string): void => {
  Cookies.remove(getCookieKey(name))
}

// 初始化并导出 cookies 实例
const cookies: CookieUtils = {
  set: setCookie,
  get: getCookie,
  getAll: getAllCookies,
  remove: removeCookie
}

export default cookies
